package com.promise.jokerdream.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.model.log.ExecutionLog
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.PhoneGameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.response.phone.FightTowerXmlResponse
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.utils.TimeUtils
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.Job

/**
 * 斗神塔ViewModel
 */
class FightTowerViewModel : ViewModel() {
    
    companion object {
        private const val TOWER_NAME = "斗神塔"
    }
    
    private val phoneGameApi = PhoneGameApi.getInstance()
    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    private val userDataManager by lazy { UserDataManager.getInstance(AppContext.get()) }
    
    // UI状态
    private val _uiState = MutableStateFlow(FightTowerUiState())
    val uiState: StateFlow<FightTowerUiState> = _uiState.asStateFlow()
    
    // 用户ID
    private var userId: String? = null
    
    // 当前执行的任务
    private var currentJob: Job? = null
    
    /**
     * 设置用户ID
     */
    fun setUserId(userId: String) {
        this.userId = userId
        // 加载用户配置
        loadUserConfig()
        // 开始监听斗神塔相关的日志
        startListeningToTowerLogs()
    }
    
    /**
     * 加载用户配置
     */
    private fun loadUserConfig() {
        val currentAccount = userDataManager.getCurrentAccount()
        val config = currentAccount?.config?.gameConfig?.fightTowerConfig
        val sundayUseUpCount = config?.sundayUseUpCount ?: false
        updateState { copy(sundayUseUpCount = sundayUseUpCount) }
    }
    
    /**
     * 保存周日用完次数配置
     */
    private fun saveSundayUseUpCountConfig(sundayUseUpCount: Boolean) {
        val currentAccount = userDataManager.getCurrentAccount() ?: return
        val currentConfig = currentAccount.config
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                fightTowerConfig = currentConfig.gameConfig.fightTowerConfig.copy(
                    sundayUseUpCount = sundayUseUpCount
                )
            )
        )
        val updatedAccount = currentAccount.copy(config = newConfig)
        userDataManager.saveUserAccount(updatedAccount)
    }
    
    /**
     * 开始监听斗神塔相关的日志
     */
    private fun startListeningToTowerLogs() {
        viewModelScope.launch {
            historyManager.getCurrentUserLogsByOperation(TOWER_NAME).collect { logs ->
                updateState { copy(executionLogs = logs) }
            }
        }
    }
    
    /**
     * 加载斗神塔数据
     */
    fun loadTowerData() {
        currentJob = viewModelScope.launch {
            phoneGameApi.queryTowerFightData().fold(
                onSuccess = { towerData ->
                    updateState { 
                        copy(
                            towerData = towerData
                        ) 
                    }
                    handleEvent(TowerEvent.DataLoaded)
                },
                onFailure = { exception ->
                    // 如果是系统繁忙，延时1秒后重新执行
                    val message = exception.message
                    if (message == "很抱歉，系统繁忙，请稍后再试!") {
                        handleEvent(TowerEvent.SystemBusy(message))
                    } else {
                        handleEvent(TowerEvent.Error(message ?: "未知错误"))
                    }
                }
            )
        }
    }
    
    /**
     * 切换周日用完次数
     */
    fun toggleSundayUseUpCount() {
        val newValue = !_uiState.value.sundayUseUpCount
        updateState { copy(sundayUseUpCount = newValue) }
        saveSundayUseUpCountConfig(newValue)
    }
    
    /**
     * 开始一键执行
     */
    fun startOneClickTask() {
        if (userId == null) return
        
        handleEvent(TowerEvent.StartTask)
    }
    
    /**
     * 停止当前任务
     */
    fun stopCurrentTask() {
        currentJob?.cancel()
        currentJob = null
        handleEvent(TowerEvent.CancelTask)
    }
    
    /**
     * 状态机核心：处理事件并转换状态
     */
    private fun handleEvent(event: TowerEvent) {
        val currentState = _uiState.value.currentState
        
        when (currentState) {
            TowerState.IDLE -> {
                when (event) {
                    is TowerEvent.StartTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.LOADING_DATA,
                                isTaskRunning = true,
                                hasTriedAutoChallenge = false
                            ) 
                        }
                        loadTowerData()
                    }
                    is TowerEvent.CancelTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.IDLE,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    else -> { /* 忽略其他事件 */ }
                }
            }
            
            TowerState.LOADING_DATA -> {
                when (event) {
                    is TowerEvent.DataLoaded -> {
                        val towerData = _uiState.value.towerData
                        when {
                            towerData?.startChallengeUrl?.isNotEmpty() == true -> {
                                // 有开始挑战URL，先检查分享上限
                                updateState { copy(currentState = TowerState.CHECKING_SHARE_LIMIT) }
                                checkShareLimitBeforeChallenge()
                            }
                            towerData?.nextFloorUrl?.isNotEmpty() == true -> {
                                // 没有开始挑战URL，但有下一层URL，直接挑战下一层
                                updateState { copy(currentState = TowerState.CHALLENGING_FLOOR) }
                                executeNextFloor(towerData.nextFloorUrl)
                            }
                            towerData?.endChallengeUrl?.isNotEmpty() == true -> {
                                // 没有其他URL，但有结束挑战URL，结束挑战
                                updateState { copy(currentState = TowerState.ENDING_CHALLENGE) }
                                executeEndChallenge()
                            }
                            else -> {
                                // 没有任何可用的URL，任务完成
                                updateState { 
                                    copy(
                                        currentState = TowerState.COMPLETED,
                                        isTaskRunning = false
                                    ) 
                                }
                            }
                        }
                    }
                    is TowerEvent.SystemBusy -> {
                        // 系统繁忙，延时重试
                        currentJob = viewModelScope.launch {
                            kotlinx.coroutines.delay(1000)
                            loadTowerData()
                        }
                    }
                    is TowerEvent.Error -> {
                        updateState { 
                            copy(
                                currentState = TowerState.FAILED,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    is TowerEvent.CancelTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.IDLE,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    else -> { /* 忽略其他事件 */ }
                }
            }
            
            TowerState.CHECKING_SHARE_LIMIT -> {
                when (event) {
                    is TowerEvent.ShareLimitChecked -> {
                        // 分享上限检查完成，开始挑战
                        val towerData = _uiState.value.towerData
                        updateState { copy(currentState = TowerState.STARTING_CHALLENGE) }
                        executeStartChallenge(towerData?.startChallengeUrl ?: "")
                    }
                    is TowerEvent.AutoChallengeBeforeStart -> {
                        // 分享达到上限，直接进行自动挑战
                        updateState { copy(currentState = TowerState.AUTO_CHALLENGING) }
                        executeAutoChallenge()
                    }
                    is TowerEvent.Error -> {
                        // 检查分享上限失败，直接开始挑战
                        val towerData = _uiState.value.towerData
                        updateState { copy(currentState = TowerState.STARTING_CHALLENGE) }
                        executeStartChallenge(towerData?.startChallengeUrl ?: "")
                    }
                    is TowerEvent.CancelTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.IDLE,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    else -> { /* 忽略其他事件 */ }
                }
            }
            
            TowerState.STARTING_CHALLENGE -> {
                when (event) {
                    is TowerEvent.ChallengeStarted -> {
                        val towerData = _uiState.value.towerData
                        if (towerData?.nextFloorUrl?.isNotEmpty() == true) {
                            updateState { copy(currentState = TowerState.CHALLENGING_FLOOR) }
                            executeNextFloor(towerData.nextFloorUrl)
                        } else if (towerData?.endChallengeUrl?.isNotEmpty() == true) {
                            // 没有下一层，直接结束挑战
                            updateState { copy(currentState = TowerState.ENDING_CHALLENGE) }
                            executeEndChallenge()
                        } else {
                            // 没有更多操作，任务完成
                            updateState { 
                                copy(
                                    currentState = TowerState.COMPLETED,
                                    isTaskRunning = false
                                ) 
                            }
                        }
                    }
                    is TowerEvent.SystemBusy -> {
                        currentJob = viewModelScope.launch {
                            kotlinx.coroutines.delay(1000)
                            executeStartChallenge(_uiState.value.towerData?.startChallengeUrl ?: "")
                        }
                    }
                    is TowerEvent.Error -> {
                        updateState { 
                            copy(
                                currentState = TowerState.FAILED,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    is TowerEvent.CancelTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.IDLE,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    else -> { /* 忽略其他事件 */ }
                }
            }
            
            TowerState.CHALLENGING_FLOOR -> {
                when (event) {
                    is TowerEvent.FloorCompleted -> {
                        val towerData = _uiState.value.towerData
                        if (towerData?.currentFloor?.rem(10) == 0 && towerData.nextFloorUrl.isNotEmpty()) {
                            // 需要分享
                            updateState { copy(currentState = TowerState.SHARING) }
                            executeShare()
                        } else if (towerData?.nextFloorUrl?.isNotEmpty() == true) {
                            // 不需要分享，直接挑战下一层
                            executeNextFloor(towerData.nextFloorUrl)
                        } else if (towerData?.endChallengeUrl?.isNotEmpty() == true) {
                            // 没有下一层，结束挑战
                            updateState { copy(currentState = TowerState.ENDING_CHALLENGE) }
                            executeEndChallenge()
                        } else {
                            // 没有更多操作，任务完成
                            updateState { 
                                copy(
                                    currentState = TowerState.COMPLETED,
                                    isTaskRunning = false
                                ) 
                            }
                        }
                    }
                    is TowerEvent.SystemBusy -> {
                        currentJob = viewModelScope.launch {
                            kotlinx.coroutines.delay(1000)
                            executeNextFloor(_uiState.value.towerData?.nextFloorUrl ?: "")
                        }
                    }
                    is TowerEvent.Error -> {
                        updateState { 
                            copy(
                                currentState = TowerState.FAILED,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    is TowerEvent.CancelTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.IDLE,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    else -> { /* 忽略其他事件 */ }
                }
            }
            
            TowerState.SHARING -> {
                when (event) {
                    is TowerEvent.ShareCompleted -> {
                        val towerData = _uiState.value.towerData
                        if (towerData?.nextFloorUrl?.isNotEmpty() == true) {
                            // 分享完成，继续挑战下一层
                            updateState { copy(currentState = TowerState.CHALLENGING_FLOOR) }
                            executeNextFloor(towerData.nextFloorUrl)
                        } else if (towerData?.endChallengeUrl?.isNotEmpty() == true) {
                            // 没有下一层，结束挑战
                            updateState { copy(currentState = TowerState.ENDING_CHALLENGE) }
                            executeEndChallenge()
                        } else {
                            // 没有更多操作，任务完成
                            updateState { 
                                copy(
                                    currentState = TowerState.COMPLETED,
                                    isTaskRunning = false
                                ) 
                            }
                        }
                    }
                    is TowerEvent.ShareLimitReached -> {
                        if (!_uiState.value.hasTriedAutoChallenge) {
                            updateState { copy(currentState = TowerState.AUTO_CHALLENGING) }
                            executeAutoChallenge()
                        } else {
                            val towerData = _uiState.value.towerData
                            if (towerData?.nextFloorUrl?.isNotEmpty() == true) {
                                // 自动挑战失败或不可用，继续挑战下一层
                                updateState { copy(currentState = TowerState.CHALLENGING_FLOOR) }
                                executeNextFloor(towerData.nextFloorUrl)
                            } else if (towerData?.endChallengeUrl?.isNotEmpty() == true) {
                                // 没有下一层，结束挑战
                                updateState { copy(currentState = TowerState.ENDING_CHALLENGE) }
                                executeEndChallenge()
                            } else {
                                // 没有更多操作，任务完成
                                updateState { 
                                    copy(
                                        currentState = TowerState.COMPLETED,
                                        isTaskRunning = false
                                    ) 
                                }
                            }
                        }
                    }
                    is TowerEvent.Error -> {
                        // 分享失败不影响流程
                        val towerData = _uiState.value.towerData
                        if (towerData?.nextFloorUrl?.isNotEmpty() == true) {
                            // 分享失败，继续挑战下一层
                            updateState { copy(currentState = TowerState.CHALLENGING_FLOOR) }
                            executeNextFloor(towerData.nextFloorUrl)
                        } else if (towerData?.endChallengeUrl?.isNotEmpty() == true) {
                            // 没有下一层，结束挑战
                            updateState { copy(currentState = TowerState.ENDING_CHALLENGE) }
                            executeEndChallenge()
                        } else {
                            // 没有更多操作，任务完成
                            updateState { 
                                copy(
                                    currentState = TowerState.COMPLETED,
                                    isTaskRunning = false
                                ) 
                            }
                        }
                    }
                    is TowerEvent.CancelTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.IDLE,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    else -> { /* 忽略其他事件 */ }
                }
            }
            
            TowerState.AUTO_CHALLENGING -> {
                when (event) {
                    is TowerEvent.AutoChallengeCompleted -> {
                        updateState { 
                            copy(
                                currentState = TowerState.ENDING_CHALLENGE,
                                hasTriedAutoChallenge = true
                            ) 
                        }
                        // 自动挑战成功，直接结束挑战
                        executeEndChallenge()
                    }
                    is TowerEvent.SystemBusy -> {
                        currentJob = viewModelScope.launch {
                            kotlinx.coroutines.delay(1000)
                            executeAutoChallenge()
                        }
                    }
                    is TowerEvent.Error -> {
                        updateState { 
                            copy(
                                currentState = TowerState.FAILED,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    is TowerEvent.CancelTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.IDLE,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    else -> { /* 忽略其他事件 */ }
                }
            }
            
            TowerState.ENDING_CHALLENGE -> {
                when (event) {
                    is TowerEvent.ChallengeEnded -> {
                        // 挑战结束后，判断是否需要周日用完次数
                        val towerData = _uiState.value.towerData
                        val hasPaidCount = towerData?.weeklyPaidCount ?: 0 > 0
                        
                        if (_uiState.value.sundayUseUpCount && TimeUtils.isSundayTime() && hasPaidCount) {
                            // 勾选了周日用完次数、当前是周日时间、且有剩余付费次数，继续挑战
                            updateState { copy(currentState = TowerState.LOADING_DATA) }
                            loadTowerData()
                        } else {
                            // 不满足条件，任务完成
                            updateState { 
                                copy(
                                    currentState = TowerState.COMPLETED,
                                    isTaskRunning = false
                                ) 
                            }
                            // 结束挑战后，重新拉取数据
                            loadTowerData()
                        }
                    }
                    is TowerEvent.Error -> {
                        updateState { 
                            copy(
                                currentState = TowerState.FAILED,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    is TowerEvent.SystemBusy -> {
                        currentJob = viewModelScope.launch {
                            kotlinx.coroutines.delay(1000)
                            executeEndChallenge()
                        }
                    }
                    is TowerEvent.CancelTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.IDLE,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    else -> { /* 忽略其他事件 */ }
                }
            }
            
            TowerState.FAILED -> {
                when (event) {
                    is TowerEvent.StartTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.LOADING_DATA,
                                isTaskRunning = true,
                                hasTriedAutoChallenge = false
                            ) 
                        }
                        loadTowerData()
                    }
                    is TowerEvent.CancelTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.IDLE,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    else -> { /* 忽略其他事件 */ }
                }
            }
            
            TowerState.COMPLETED -> {
                when (event) {
                    is TowerEvent.StartTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.LOADING_DATA,
                                isTaskRunning = true,
                                hasTriedAutoChallenge = false
                            ) 
                        }
                        loadTowerData()
                    }
                    is TowerEvent.CancelTask -> {
                        updateState { 
                            copy(
                                currentState = TowerState.IDLE,
                                isTaskRunning = false
                            ) 
                        }
                    }
                    else -> { /* 忽略其他事件 */ }
                }
            }
        }
    }
    
    
    /**
     * 检查分享上限（在开始挑战前）
     */
    private fun checkShareLimitBeforeChallenge() {
        if (userId == null) return
        
        currentJob = viewModelScope.launch {
            // 查询分享信息
            gameApi.queryPenguinShare().foldWithApiException(
                onSuccess = { shareResponse ->
                    // 判断是否达到分享上限
                    if (shareResponse.dayShareTimes >= shareResponse.dayMaxShareTimes) {
                        // 达到上限，直接进行自动挑战
                        handleEvent(TowerEvent.AutoChallengeBeforeStart)
                    } else {
                        // 未达到上限，继续正常流程
                        handleEvent(TowerEvent.ShareLimitChecked)
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(TOWER_NAME, msg, code)
                    // 查询失败，继续正常流程
                    handleEvent(TowerEvent.ShareLimitChecked)
                }
            )
        }
    }
    
    /**
     * 执行分享操作
     */
    private fun executeShare() {
        if (userId == null) return
        
        currentJob = viewModelScope.launch {
            // 先查询分享信息
            gameApi.queryPenguinShare().foldWithApiException(
                onSuccess = { shareResponse ->
                    // 判断是否达到分享上限
                    if (shareResponse.dayShareTimes >= shareResponse.dayMaxShareTimes) {
                        updateState { copy(isShareLimitReached = true) }
                        handleEvent(TowerEvent.ShareLimitReached)
                        return@launch
                    }
                    
                    // 未达到上限，执行分享
                    gameApi.shareGame(4).foldWithApiException(
                        onSuccess = { response ->
                            historyManager.addHistory(TOWER_NAME, response.msg)
                            if (isSystemBusyMessage(response.msg)) {
                                handleEvent(TowerEvent.SystemBusy(response.msg))
                            } else {
                                // 分享成功后，检查是否达到分享上限
                                if (shareResponse.dayShareTimes + 1 >= shareResponse.dayMaxShareTimes) {
                                    updateState { copy(isShareLimitReached = true) }
                                    handleEvent(TowerEvent.ShareLimitReached)
                                } else {
                                    handleEvent(TowerEvent.ShareCompleted)
                                }
                            }
                        },
                        onFailure = { code, msg ->
                            historyManager.addHistory(TOWER_NAME, msg, code)
                            if (isSystemBusyMessage(msg)) {
                                handleEvent(TowerEvent.SystemBusy(msg))
                            } else {
                                handleEvent(TowerEvent.Error(msg))
                            }
                        }
                    )
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(TOWER_NAME, msg, code)
                    handleEvent(TowerEvent.Error(msg))
                }
            )
        }
    }
    
    /**
     * 执行自动挑战
     */
    private fun executeAutoChallenge() {
        val towerData = _uiState.value.towerData ?: return
        
        // 检查是否有自动挑战URL
        if (towerData.autoChallengeUrl.isNotEmpty()) {
            currentJob = viewModelScope.launch {
                phoneGameApi.executeTowerAction(towerData.autoChallengeUrl).fold(
                    onSuccess = { response ->
                    historyManager.addHistory(TOWER_NAME, response.actionResult)
                        if (isSystemBusyMessage(response.actionResult)) {
                            handleEvent(TowerEvent.SystemBusy(response.actionResult))
                        } else {
                            updateState {
                                copy(towerData = response)
                            }
                            handleEvent(TowerEvent.AutoChallengeCompleted)
                        }
                    },
                    onFailure = { exception ->
                        historyManager.addHistory(TOWER_NAME, exception.message)
                        
                        // 如果是系统繁忙，延时1秒后重新执行
                        val message = exception.message
                        if (message == "很抱歉，系统繁忙，请稍后再试！") {
                            handleEvent(TowerEvent.SystemBusy(message))
                        } else {
                            handleEvent(TowerEvent.Error(message ?: "未知错误"))
                        }
                    }
                )
            }
        } else {
            // 没有自动挑战URL，直接完成
            handleEvent(TowerEvent.AutoChallengeCompleted)
        }
    }
    
    /**
     * 执行开始挑战
     */
    private fun executeStartChallenge(url: String) {
        if (userId == null) return
        
        currentJob = viewModelScope.launch {
            phoneGameApi.executeTowerAction(url).fold(
                onSuccess = { response ->
                    historyManager.addHistory(TOWER_NAME, response.actionResult)
                    if (isSystemBusyMessage(response.actionResult)) {
                        handleEvent(TowerEvent.SystemBusy(response.actionResult))
                    } else {
                        updateState { 
                            copy(towerData = response) 
                        }
                        handleEvent(TowerEvent.ChallengeStarted)
                    }
                },
                onFailure = { exception ->
                    historyManager.addHistory(TOWER_NAME, exception.message)
                    
                    // 如果是系统繁忙，延时1秒后重新执行
                    val message = exception.message
                    if (message == "很抱歉，系统繁忙，请稍后再试！") {
                        handleEvent(TowerEvent.SystemBusy(message))
                    } else {
                        handleEvent(TowerEvent.Error(message ?: "未知错误"))
                    }
                }
            )
        }
    }
    
    /**
     * 执行挑战下一层
     */
    private fun executeNextFloor(url: String) {
        if (userId == null) return
        
        currentJob = viewModelScope.launch {
            // 执行前判断剩余战斗时间
            val currentTowerData = _uiState.value.towerData
            if ((currentTowerData?.remainingBattleTime ?: 0) > 0) {
                kotlinx.coroutines.delay(currentTowerData!!.remainingBattleTime * 1000L)
            }
            
            phoneGameApi.executeTowerAction(url).fold(
                onSuccess = { response ->
                    historyManager.addHistory(TOWER_NAME, response.actionResult)
                    if (isSystemBusyMessage(response.actionResult)) {
                        handleEvent(TowerEvent.SystemBusy(response.actionResult))
                    } else {
                        updateState {
                            copy(towerData = response) 
                        }
                        handleEvent(TowerEvent.FloorCompleted)
                    }
                },
                onFailure = { exception ->
                    historyManager.addHistory(TOWER_NAME, exception.message)
                    
                    // 如果是系统繁忙，延时1秒后重新执行
                    val message = exception.message
                    if (message == "很抱歉，系统繁忙，请稍后再试！") {
                        handleEvent(TowerEvent.SystemBusy(message))
                    } else {
                        handleEvent(TowerEvent.Error(message ?: "未知错误"))
                    }
                }
            )
        }
    }
    
    /**
     * 执行结束挑战
     */
    private fun executeEndChallenge() {
        if (userId == null) return
        
        currentJob = viewModelScope.launch {
            gameApi.endTowerChallenge().foldWithApiException(
                onSuccess = { response ->
                    historyManager.addHistory(TOWER_NAME, response.msg)
                    if (isSystemBusyMessage(response.msg)) {
                        handleEvent(TowerEvent.SystemBusy(response.msg))
                    } else {
                        handleEvent(TowerEvent.ChallengeEnded)
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(TOWER_NAME, msg, code)
                    if (isSystemBusyMessage(msg)) {
                        handleEvent(TowerEvent.SystemBusy(msg))
                    } else {
                        handleEvent(TowerEvent.Error(msg))
                    }
                }
            )
        }
    }
    
    /**
     * 判断是否为系统繁忙或战斗冷却消息
     */
    private fun isSystemBusyMessage(message: String): Boolean {
        return message == "很抱歉，系统繁忙，请稍后再试!" ||
               message == "战斗冷却中，请稍后再挑战"
    }
    
    /**
     * 更新状态的辅助方法
     */
    private fun updateState(update: FightTowerUiState.() -> FightTowerUiState) {
        _uiState.value = _uiState.value.update()
    }
}

/**
 * 斗神塔状态机状态
 */
enum class TowerState {
    IDLE,                    // 空闲状态
    LOADING_DATA,           // 加载数据中
    CHECKING_SHARE_LIMIT,   // 检查分享上限中
    STARTING_CHALLENGE,     // 开始挑战中
    CHALLENGING_FLOOR,      // 挑战楼层中
    SHARING,                // 分享中
    AUTO_CHALLENGING,       // 自动挑战中
    ENDING_CHALLENGE,       // 结束挑战中
    FAILED,                 // 失败状态
    COMPLETED               // 完成状态
}

/**
 * 斗神塔状态机事件
 */
sealed class TowerEvent {
    object StartTask : TowerEvent()
    object DataLoaded : TowerEvent()
    object ShareLimitChecked : TowerEvent()
    object AutoChallengeBeforeStart : TowerEvent()
    object ChallengeStarted : TowerEvent()
    object FloorCompleted : TowerEvent()
    object ShareCompleted : TowerEvent()
    object ShareLimitReached : TowerEvent()
    object AutoChallengeCompleted : TowerEvent()
    object ChallengeEnded : TowerEvent()
    object CancelTask : TowerEvent()
    data class Error(val message: String) : TowerEvent()
    data class SystemBusy(val message: String) : TowerEvent()
}

/**
 * UI状态数据类
 */
data class FightTowerUiState(
    val towerData: FightTowerXmlResponse? = null,
    val isTaskRunning: Boolean = false,
    val sundayUseUpCount: Boolean = false,
    val errorMessage: String? = null,
    val executionLogs: List<ExecutionLog> = emptyList(),
    val isShareLimitReached: Boolean = false,
    val hasTriedAutoChallenge: Boolean = false,
    val currentState: TowerState = TowerState.IDLE
)